package com.springboot.service.impl;

import com.springboot.mapper.GoodsMapper;
import com.springboot.mapper.UserMapper;
import com.springboot.model.Goods;
import com.springboot.model.User;
import com.springboot.service.GoodsService;
import io.shardingsphere.api.HintManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @Author: TongRui乀
 * @Date: 2019/10/16 13:56
 * @description：
 */
@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Goods getGoodsById(Integer id) {

        HintManager hintManager = HintManager.getInstance();

        hintManager.setDatabaseShardingValue("db1");

        return this.goodsMapper.selectById(id);
    }

    @Override
    public User getUserById(Integer id) {

        return this.userMapper.selectById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertUser(User user) {

        this.userMapper.insert(user);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertGoods(Goods goods) {
        this.goodsMapper.insert(goods);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGoods(Goods goods) {

        Goods g = this.goodsMapper.selectById(goods.getId());

        log.info("修改前[{}]", g);

        try {

            this.goodsMapper.update(goods);

            int a = 1 / 0;

        }catch (Exception e){
            log.error("修改用户出错：{}",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUser(User user) {

        User user1 = this.userMapper.selectById(user.getId());

        log.info("修改前[{}]", user1);

        try{
            this.userMapper.update(user);

            int a = 1/ 0;

        } catch (Exception e){
            log.error("修改用户出错：{}",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGoodsAndUser(Goods goods, User user) {

        try{

            this.goodsMapper.update(goods);

            this.userMapper.update(user);

            int a = 1/ 0;

        } catch (Exception e){
            log.error("修改用户出错：{}",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }
}
